import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { News } from './news';



@Injectable()
export class NewsDataProvider {

  private readonly baseUrl: string = 'https://api.bmob.cn/1';
  private readonly httpHeaders : HttpHeaders = new HttpHeaders(
    {
      'X-Bmob-Application-Id':'748054e798358354bf419b92c0dd9638',
      'X-Bmob-REST-API-Key':'452b75414d0a4920470d5ff482cb451d',
      'Content-Type':'application/json'
    }
  );

  constructor(public http: HttpClient) {
    
  }

  // 返回多个数据
  /**
   * 分页获取新闻数据
   * @param num 
   * @param page 
   */
  getNews(num : number, page: number):Observable<News[]>{
    let _params = new HttpParams()
    .set('limit',`${num}`)
    .set('skip',`${(page-1)*num}`);
    return this.http.get<News[]>(`${this.baseUrl}/classes/news`,
    {headers: this.httpHeaders, params: _params}).map(_=>_['results']);
  }

  /**
   * 新增新闻
   * @param news 
   * @returns {Observable<News>} 响应结果
   */
  addNews(news : News): Observable<News>{
    let _news = {name: news.name, img: news.img, intro:news.intro, time: news.time,address:news.address};
    return this.http.post<News>(`${this.baseUrl}/classes/news`,_news,{headers: this.httpHeaders});
  }


  

  

}
